next up previous
Next: 3.6 Changed Page Sizes Up: 3 Generic 64-bit Portability Previous: 3.4 Careful Using Variable

3.5 Using inttypes.h

For most of the problems above, safe coding practices avoid the problems, but there are cases where code needs to rely on the physical sizes of data types. For example, the parser for a binary file format that has precisely sized fields may want a data structure containing fields sized to that of the binary file format. But is there a portable way to request a type with exactly 32-bits?

The straightforward way to solve the problem is to develop a set of exactly sized typedefs. For example, you could use int32 when a true 32-bit integer is desired. Then, make sure the typedef for int32 is established to be the correctly sized type in a system-specific header file. While this isolates the portability issue to a single header file, this means this system-specific header file must be updated for each specific system you plan to compile for.

To avoid foisting this general problem on every software developer, a group of vendors, including all major Unix workstation vendors, has agreed to a proposal to provide a standard header file named inttypes.h supporting new type declarations to address exactly this problem. Using inttypes.h helps you write code that is portable to any of the possible 32-bit and 64-bit C data type models.

The types defined in inttypes.h are described in Table 2. Along with the types, the inttypes.h header file defines:

In the previous examples showing portability problems that arise due to the changing size of the long type in the 32BIT versus the LP64 type models, using exactly sized types from inttypes.h would avoid the problems. For example, the struct and union declarations from the previous examples are portably rewritten as:

  #include <inttypes.h>

  union {
    uint8_t c[4];
    uint32_t l;
  } combo;

  struct header {
    int32_t tag;
    uint32_t length;
  };

Be careful using inttypes.h since older development environments may not support this header file. Also, it is conceivable a future ANSI specification may include a builtin facility for handling exactly sized types.



next up previous
Next: 3.6 Changed Page Sizes Up: 3 Generic 64-bit Portability Previous: 3.4 Careful Using Variable



Mark Kilgard
Sat Dec 30 11:52:07 PST 1995